package com.ck.javatestspace.tools.img;

import com.google.common.base.Stopwatch;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.fit.cssbox.css.CSSNorm;
import org.fit.cssbox.css.DOMAnalyzer;
import org.fit.cssbox.io.DOMSource;
import org.fit.cssbox.io.DefaultDOMSource;
import org.fit.cssbox.io.DocumentSource;
import org.fit.cssbox.io.StreamDocumentSource;
import org.fit.cssbox.layout.BrowserCanvas;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.imageio.ImageIO;
import java.awt.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author chenghai on 2021/12/29 0029. - 星期三
 * @project java-test-space
 */
@Slf4j
public class Ftl2Img {
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        prescriptionHtmlToPng();
        log.info("耗时：{}",System.currentTimeMillis()-start);
    }
    public static String prescriptionHtmlToPng() {
        Stopwatch stopwatch = Stopwatch.createStarted();
        ByteArrayOutputStream out = null;
        ByteArrayInputStream imageInputStream = null;
        InputStream is = null;
        DocumentSource docSource = null;
        String imageUrl = "";
        int width = 1240;
        int height = 854;

        try {


//            Map<String, String> templateParams = getPrescriptionInfo(prescriptionInfoVO);
            // 查询一个模版
            Configuration configuration = new Configuration(Configuration.VERSION_2_3_31);
            configuration.setDirectoryForTemplateLoading(new File("C:\\Users\\Administrator\\project\\ddjk\\java-test-space\\src\\main\\resources\\templates"));
            Template template = configuration.getTemplate("prescriptioninfo.ftl");
//            Template template = new FreeMarkerConfigurer().getConfiguration().getTemplate("prescriptioninfo.ftl");
            Map<String, String> templateParams = Maps.newHashMap();
            templateParams.put("logo", "abc");
            templateParams.put("patientName", "abc");
            templateParams.put("patientGender", "abc");
            templateParams.put("age","abc");
            templateParams.put("deptName", "abc");
            templateParams.put("prescriptionTime", "abc");
            templateParams.put("doctorName", "程海");
            templateParams.put("a", "abc");
            templateParams.put("a", "abc");
            String readyParsedTemplate = FreeMarkerTemplateUtils.processTemplateIntoString(template, templateParams);

            is = new ByteArrayInputStream(readyParsedTemplate.getBytes(StandardCharsets.UTF_8));
            docSource = new StreamDocumentSource(is, null, "text/html; charset=utf-8");

            DOMSource parser = new DefaultDOMSource(docSource);

            DOMAnalyzer da = new DOMAnalyzer(parser.parse(), docSource.getURL());
            da.attributesToStyles();
            da.addStyleSheet(null, CSSNorm.stdStyleSheet(), DOMAnalyzer.Origin.AGENT);
            da.addStyleSheet(null, CSSNorm.userStyleSheet(), DOMAnalyzer.Origin.AGENT);
            da.addStyleSheet(null, CSSNorm.formsStyleSheet(), DOMAnalyzer.Origin.AGENT);
            da.getStyleSheets();

            BrowserCanvas contentCanvas = new BrowserCanvas(da.getRoot(), da, docSource.getURL());
            contentCanvas.createLayout(new Dimension(width, height));
            out = new ByteArrayOutputStream();
            ImageIO.write(contentCanvas.getImage(), "png", new File("outpout.png"));
            imageInputStream = new ByteArrayInputStream(out.toByteArray());
//            imageUrl = ossService.uploadFileByInputStream(imageInputStream);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (is != null) {
                    is.close();
                }
                if (imageInputStream != null) {
                    imageInputStream.close();
                }
                if (docSource != null) {
                    docSource.close();
                }
                if (stopwatch != null && stopwatch.isRunning()) {
                    stopwatch.stop();
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
        return imageUrl;
    }

}
